package com.bw.zyk.zhanggm.product.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.zyk.zhanggm.product.entity.*;
import com.bw.zyk.zhanggm.product.openfein.StockFeignClient;
import com.bw.zyk.zhanggm.product.service.*;
import com.bw.zyk.zhanggm.product.vo.SpuDetailVo;
import com.bw.zyk.zhanggm.product.vo.StockVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.web.domain.AjaxResult;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * spu表，该表描述的是一个抽象性的商品，比如 iphone8 前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-04-23
 */
@RestController
@RequestMapping("/spu/")
public class SpuController {

    @Autowired
    ISpuService iSpuService;

    @Autowired
    ISpuDetailService iSpuDetailService;

    @Autowired
    IBrandService iBrandService;

    @Autowired
    ICategoryService iCategoryService;

    @Autowired
    ISkuService iSkuService;

    @Autowired
    StockFeignClient stockFeignClient;


//    @Transactional(rollbackFor = Exception.class)
//    @GlobalTransactional
    @GetMapping("page")
    public AjaxResult page(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        //分页
        PageHelper.startPage(pageNum, pageSize);
        //查询商品数据
        List<Spu> list = iSpuService.list();
        //关联商品详情
        List<Long> spuIdList = list.stream().map(item -> item.getId()).collect(Collectors.toList());
        List<SpuDetail> spuDetailList = iSpuDetailService.listByIds(spuIdList);
        Map<Long, SpuDetail> spuDetailMap = spuDetailList.stream().collect(Collectors.toMap(SpuDetail::getSpuId, item -> item));
        list.forEach(spu -> {
            spu.setSpuDetail(spuDetailMap.get(spu.getId()));
        });
        //关联品牌数据
        List<Long> brandIdList = list.stream().map(item -> item.getBrandId()).collect(Collectors.toList());
        List<Brand> brandList = iBrandService.listByIds(brandIdList);
        Map<Long, Brand> brandMap = brandList.stream().collect(Collectors.toMap(Brand::getId, item -> item));
        list.forEach(spu -> {
            spu.setBrand(brandMap.get(spu.getBrandId()));
        });
        //关联分类
        Set<Long> allCateIdSet = list.stream().map(item -> item.getCid1()).collect(Collectors.toSet());
        Set<Long> cid2Set = list.stream().map(item -> item.getCid2()).collect(Collectors.toSet());
        Set<Long> cid23et = list.stream().map(item -> item.getCid3()).collect(Collectors.toSet());
        allCateIdSet.addAll(cid2Set);
        allCateIdSet.addAll(cid23et);
        List<Category> categorieList = iCategoryService.listByIds(allCateIdSet);
        Map<Long, Category> cateMap = categorieList.stream().collect(Collectors.toMap(Category::getId, item -> item));
        list.forEach(spu -> {
            spu.setCategory1(cateMap.get(spu.getCid1()));
            spu.setCategory2(cateMap.get(spu.getCid2()));
            spu.setCategory3(cateMap.get(spu.getCid3()));
        });
        //open远程调用查询商品总库存,返回map，key是skuId，value是数据量
        LambdaQueryWrapper<Sku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Sku::getSpuId, spuIdList);
        List<Sku> skuList = iSkuService.list(queryWrapper);
        //远程调用查询库存
        List<Long> skuIdList = skuList.stream().map(item -> item.getId()).collect(Collectors.toList());
        List<StockVo> stockVoList = stockFeignClient.getListByIds(skuIdList);
        list.forEach(spu -> {
            List<Long> skuIds = skuList.stream().filter(item -> item.getSpuId().equals(spu.getId())).map(item -> item.getId()).collect(Collectors.toList());
            Long sum = stockVoList.stream().filter(item -> skuIds.contains(item.getSkuId())).mapToLong(item -> item.getStock()).sum();
            spu.setStock(sum);
        });
        return AjaxResult.success(new PageInfo<>(list));
    }

    //@SentinelResource(value = "productSpu")
    @GetMapping("detail/{id}")
    public AjaxResult detail(@PathVariable Integer id) {
        //查询商品
        Spu spu = iSpuService.getById(id);
        //查询商品详情
        SpuDetail spuDetail = iSpuDetailService.getById(id);
        //查询商品对应的sku，可以售卖列表
        LambdaQueryWrapper<Sku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Sku::getSpuId, id);
        List<Sku> skuList = iSkuService.list(queryWrapper);
        //设置vo
        SpuDetailVo spuDetailVo = new SpuDetailVo();
        spuDetailVo.setSpu(spu);
        spuDetailVo.setSpuDetail(spuDetail);
        spuDetailVo.setSkuList(skuList);
        return AjaxResult.success(spuDetailVo);
    }


}
